package com.weixu.fileconver.controller;

import com.weixu.fileconver.entity.ApiResponse;
import com.weixu.fileconver.entity.ConvertResult;
import com.weixu.fileconver.service.FileConvertService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件转换控制器
 *
 * @Author weixu
 * @Date 2025/8/29
 */
@RestController
@RequestMapping("/api")
public class FileConvertController {

    private static final Logger logger = LoggerFactory.getLogger(FileConvertController.class);
    @Autowired
    private FileConvertService fileConvertService;

    /**
     * 文件转换接口（支持多种格式）- 直接返回文件流
     *
     * @param file       上传的文件
     * @param targetType 转换目标格式，例如 "pdf", "docx", "xlsx" 等
     * @return 转换后的文件流
     */
    @PostMapping("/convert")
    public ResponseEntity<InputStreamResource> convertToFormat(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "targetType", defaultValue = "pdf") String targetType) {

        try {
            logger.info("收到文件转换请求: 文件名={}, 大小={} bytes, 目标格式={}",
                    file.getOriginalFilename(), file.getSize(), targetType);

            // 执行转换并获取结果
            ConvertResult result = fileConvertService.convertToFormatWithInfo(file, targetType);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = URLEncoder.encode(result.getFileName(), StandardCharsets.UTF_8.name())
                    .replaceAll("\\+", "%20");
            headers.add(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.add(HttpHeaders.CONTENT_TYPE, result.getContentType());
            headers.add("X-Original-Filename", file.getOriginalFilename());
            headers.add("X-Target-Format", targetType);
            headers.add("X-File-Size", String.valueOf(result.getFileSize()));

            logger.info("文件转换成功: {} -> {} (格式: {})", file.getOriginalFilename(),
                    result.getFileName(), targetType);

            // 返回文件流
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(result.getFileSize())
                    .contentType(MediaType.parseMediaType(result.getContentType()))
                    .body(new InputStreamResource(result.getInputStream()));

        } catch (Exception e) {
            logger.error("文件转换失败: {}", e.getMessage(), e);
            // 转换失败时返回错误信息
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
            String errorJson = "{\"error\":\"文件转换失败: " + e.getMessage().replace("\"", "\\\"") +
                    "\"}";
            return ResponseEntity.badRequest()
                    .headers(headers)
                    .body(new InputStreamResource(new java.io.ByteArrayInputStream(errorJson.getBytes())));
        }
    }

    /**
     * 文件转换信息接口（返回JSON格式的转换信息）
     *
     * @param file       上传的文件
     * @param targetType 转换目标格式
     * @return 转换结果信息
     */
    @PostMapping("/convert-info")
    public ApiResponse<Map<String, Object>> convertToFormatInfo(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "targetType", defaultValue = "pdf") String targetType) {

        try {
            logger.info("收到文件转换信息请求: 文件名={}, 大小={} bytes, 目标格式={}",
                    file.getOriginalFilename(), file.getSize(), targetType);

            // 执行转换并获取结果
            ConvertResult result = fileConvertService.convertToFormatWithInfo(file, targetType);

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("originalFileName", result.getOriginalFileName());
            responseData.put("convertedFileName", result.getFileName());
            responseData.put("fileSize", result.getFileSize());
            responseData.put("targetFormat", result.getTargetFormat());
            responseData.put("contentType", result.getContentType());
            responseData.put("downloadUrl", "/api/convert?file=" + file.getOriginalFilename() +
                    "&targetType=" + targetType);

            logger.info("文件转换信息获取成功: {} -> {} (格式: {})",
                    file.getOriginalFilename(), result.getFileName(), targetType);

            return ApiResponse.success("文件转换信息获取成功", responseData);

        } catch (Exception e) {
            logger.error("文件转换失败: {}", e.getMessage(), e);
            return ApiResponse.error("文件转换失败: " + e.getMessage());
        }
    }

    /**
     * 检查支持的文件格式
     *
     * @return 支持的文件格式列表
     */
    @GetMapping("/supported-formats")
    public ApiResponse<Map<String, Object>> getSupportedFormats() {
        Map<String, Object> result = new HashMap<>();

        // 支持的输入格式
        String[] inputFormats = {
                "doc", "docx", "xls", "xlsx", "ppt", "pptx",
                "odt", "ods", "odp", "rtf", "txt", "pdf"
        };

        // 支持的输出格式
        String[] outputFormats = {
                "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx",
                "odt", "ods", "odp", "rtf", "txt", "html", "csv"
        };

        // 格式转换兼容性说明
        Map<String, Object> compatibility = new HashMap<>();
        compatibility.put("universal", new String[]{"pdf", "html", "txt", "rtf"});
        compatibility.put("word", new String[]{"doc", "docx", "odt", "pdf", "html", "txt", "rtf"});
        compatibility.put("excel", new String[]{"xls", "xlsx", "ods", "csv", "pdf", "html", "txt"
                , "rtf"});
        compatibility.put("powerpoint", new String[]{"ppt", "pptx", "odp", "pdf", "html", "txt",
                "rtf"});
        compatibility.put("libreoffice", new String[]{"odt", "ods", "odp", "pdf", "html", "txt",
                "rtf"});
        compatibility.put("pdf", new String[]{"docx", "txt", "html", "rtf"});

        result.put("inputFormats", inputFormats);
        result.put("outputFormats", outputFormats);
        result.put("compatibility", compatibility);
        result.put("maxFileSize", "10MB");
        result.put("description", "支持LibreOffice的多种格式转换，包括PDF转DOCX，但存在格式兼容性限制");
        result.put("note", "不同类型的文档格式之间不能直接转换（如Word转Excel）。PDF可以转换为DOCX（使用特殊过滤器）、TXT、HTML、RTF格式");

        return ApiResponse.success("获取支持格式成功", result);
    }

    /**
     * 检查LibreOffice服务状态
     *
     * @return 服务状态
     */
    @GetMapping("/status")
    public ApiResponse<Map<String, Object>> getServiceStatus() {
        Map<String, Object> result = new HashMap<>();

        boolean isAvailable = fileConvertService.isLibreOfficeAvailable();
        result.put("libreOfficeAvailable", isAvailable);
        if (isAvailable) {
            return ApiResponse.success("服务状态正常", result);
        } else {
            return ApiResponse.error(500, "LibreOffice服务不可用");
        }
    }
}